'use strict';

const db = uniCloud.database();
const dbcmd = db.command;

exports.main = async (event, context) => {
	let response = {
		code: 0,
		datas: {
			received: {
				count: 0
			},
			completed: {
				count: 0
			},
			aftersale: {
				count: 0
			},
			coupon: {
				count: 0
			}
		}
	};
	const ip = context.CLIENTIP;
	const orderParameterRes = await db.collection('wmzmall-order-parameter')
		.field({
			overdue_minute_cancel_order: true,
			overdue_day_receiving: true,
			overdue_day_close_evaluated: true,
			overdue_day_close_aftersale: true,
		})
		.limit(1)
		.get();
	const [orderParameter] = orderParameterRes.data;

	// 发货后 超过 7天，自动确认收货
	response.datas.received.count = await doReceivedOrder(ip, orderParameter);
	
	// 收货后 超过 15天，关闭评价订单改为已完成，并奖励积分
	response.datas.completed.count = await doCompletedOrder(ip, orderParameter);
	
	// 收货后 超过 15天，关闭售后入口
	response.datas.aftersale.count = await doAfterSaleOrder(ip, orderParameter);
	
	// 处理已过期优惠券
	response.datas.coupon.count = await doExpireCoupon(ip);
	
	//返回数据给客户端
	return response;
};

// 发货后 超过 7天，自动确认收货
// overdue_day_receiving
const doReceivedOrder = async (ip, orderParameter) => {
	const receivedOrderTime = orderParameter.overdue_day_receiving || 7;
	let count = 0;
	let receivedRes = {};
	do {
		// 订单确认收货
		receivedRes = await receivedOrder(ip, receivedOrderTime);
		count += receivedRes.count;
	} while (receivedRes.count >= 300)
	
	return count;
}
const receivedOrder = async (ip, receivedOrderTime = 7) => {
	const nowdate = Date.now();
	const res = {
		count: 0
	};
	
	// 针对之前的老数据，可以使用 last_modify_time 替换 deliver_time，右键 order-job 运行-本地云函数 执行一次
	// last_modify_time: dbcmd.lte(nowdate - receivedOrderTime * 24 * 60 * 60 * 1000)
	// deliver_time: dbcmd.lte(nowdate - receivedOrderTime * 24 * 60 * 60 * 1000)
	const orderRes = await db.collection('wmzmall-order')
		.where({
			state: '待收货',
			// 发货时间
			deliver_time: dbcmd.lte(nowdate - receivedOrderTime * 24 * 60 * 60 * 1000)
		})
		.field({
			order_actural_paid: true,
			order_id: true,
			is_fxs: true,
			is_settlement: true,
			order_fxs_uid: true,
			order_fxs_amount: true,
			order_fxs_uid2: true,
			order_fxs_amount2: true,
			order_member_name: true,
			order_member_openid: true,
			order_member_headimg: true,
			order_info: true,
			order_goods_cnt: true,
			create_uid: true
		})
		.limit(300)
		.get();
	
	if (orderRes.data && orderRes.data.length > 0) {
		res.count = orderRes.data.length;
	
		const orderIds = [];
		const orderLogs = [];
		
		for (let i = 0; i < orderRes.data.length; i++) {
			let order = orderRes.data[i];
			let orderUpdate = {
				state: '待评价',
				
				// 收货时间
				received_time: nowdate,
				received_uid: 'job-day',
				received_uname: 'job-day',
				last_modify_time: nowdate,
				last_modify_uid: 'job-day'
			}
			
			// 分销订单
			if (order.is_fxs == '是' && order.is_settlement == '否') {
				if (order.order_fxs_uid && order.order_fxs_amount) {
					// 1. 分销商可提现金额
					await db.collection('wmzmall-distributor').doc(order.order_fxs_uid).update({
						fxs_unsettled_amount: db.command.inc(-order.order_fxs_amount),
						fxs_cashout_amount: db.command.inc(order.order_fxs_amount),
						version: db.command.inc(1),
				
						last_modify_uid: 'job-day',
						last_modify_time: nowdate
					});
					// 2. 分销记录状态 已结算
					await db.collection('wmzmall-distributor-record').where({
						fxs_uid: order.order_fxs_uid,
						order_id: order.order_id
					}).update({
						version: db.command.inc(1),
						state: '已结算',
				
						last_modify_uid: 'job-day',
						last_modify_time: nowdate
					});
				
					// 3. 分销操作日志
					await db.collection('wmzmall-distributor-log').add({
						fxs_uid: order.order_fxs_uid,
						oper_content: `结算订单[+${order.order_id}]收益`,
						oper_type: '下单收益',
						oper_ip: ip,
						remark: `下级会员[${order.order_member_name}]下单[+${order.order_fxs_amount / 100}]`,
						version: 1,
						is_delete: 0,
						create_uid: 'job-day',
						create_time: nowdate
					});
				}
			
				if (order.order_fxs_uid2 && order.order_fxs_amount2) {
					// 1. 上上级分销商可提现金额
					await db.collection('wmzmall-distributor').doc(order.order_fxs_uid2).update({
						fxs_unsettled_amount: db.command.inc(-order.order_fxs_amount2),
						fxs_cashout_amount: db.command.inc(order.order_fxs_amount2),
						version: db.command.inc(1),
					
						last_modify_uid: 'job-day',
						last_modify_time: nowdate
					});
					// 2. 上上级分销记录状态 已结算
					await db.collection('wmzmall-distributor-record').where({
						fxs_uid: order.order_fxs_uid2,
						order_id: order.order_id
					}).update({
						version: db.command.inc(1),
						state: '已结算',
					
						last_modify_uid: 'job-day',
						last_modify_time: nowdate
					});
					
					// 3. 上上级分销操作日志
					await db.collection('wmzmall-distributor-log').add({
						fxs_uid: order.order_fxs_uid2,
						oper_content: `结算订单[+${order.order_id}]收益`,
						oper_type: '下单收益',
						oper_ip: ip,
						remark: `下下级会员[${order.order_member_name}]下单[+${order.order_fxs_amount2 / 100}]`,
						version: 1,
						is_delete: 0,
						create_uid: 'job-day',
						create_time: nowdate
					});
				}
				
				// 4. 分销订单已结算
				orderUpdate.is_settlement = '是';
				orderUpdate.settlement_time = nowdate;
			}
			
			// 修改订单为待评价
			await db.collection('wmzmall-order')
				.doc(order._id)
				.update(orderUpdate);
				
			orderLogs.push({
				order_id: order.order_id,
				log_type: '确认收货',
				remark: `待收货超过 ${receivedOrderTime} 天，自动确认收货`,
				current_state: '待评价',
				prev_state: '待收货',
				ip: ip,
				is_delete: 0,
				create_uid: 'job-day',
				create_time: nowdate
			});
		}
	
		res.addLogRes = await db.collection('wmzmall-order-log').add(orderLogs);
	}
	
	return res;
}

// 收货后 超过 15天，关闭评价订单改为已完成
// overdue_day_close_evaluated
const doCompletedOrder = async (ip, orderParameter) => {
	const configTime = orderParameter.overdue_day_close_evaluated || 7;
	let count = 0;
	let res = {};
	do {
		// 订单已完成
		res = await completedOrder(ip, configTime);
		count += res.count;
	} while (res.count >= 300)
	
	return count;
}
const completedOrder = async (ip, configTime = 15) => {
	const nowdate = Date.now();
	const res = {
		count: 0
	};
	
	const orderRes = await db.collection('wmzmall-order')
		.where({
			state: '待评价',
			// 收货时间 超过 15天
			received_time: dbcmd.lte(nowdate - configTime * 24 * 60 * 60 * 1000)
		})
		.field({
			order_id: true,
			create_uid: true,
			order_return_integral: true
		})
		.limit(300)
		.get();
	
	if (orderRes.data && orderRes.data.length > 0) {
		res.count = orderRes.data.length;
		
		const nowtime = toDateUTC8(new Date());
		const time = `${nowtime.getFullYear()}-${nowtime.getMonth() + 1}-${nowtime.getDate()} ${nowtime.getHours()}:${nowtime.getMinutes()}`;
		
		const orderIds = [];
		const orderLogs = [];
		
		for (let i = 0; i < orderRes.data.length; i++) {
			let order = orderRes.data[i];
			
			orderIds.push(order._id);
			orderLogs.push({
				order_id: order.order_id,
				log_type: '订单已完成',
				remark: `收货后超过 ${configTime} 天，关闭评价订单改为已完成`,
				current_state: '已完成',
				prev_state: '待评价',
				ip: ip,
				is_delete: 0,
				create_uid: 'job-day',
				create_time: nowdate
			});
			
			// 奖励下单人积分
			let uid = order.create_uid;
			let integral = order.order_return_integral;
			
			if (integral > 0) {
				await db.collection('wmzmall-member').doc(uid).update({
					member_integral: db.command.inc(integral),
					member_integral_surplus: db.command.inc(integral),
					member_integral_total: db.command.inc(integral)
				});
				
				// 记录积分数据
				await dbtran.collection('wmzmall-integral-record').add({
					member_id: uid,
					member_uid: uid,
					integral: integral,
					type: '收入',
					source: '下单',
					order_id: order.order_id,
					goods_id: '',
					remark: `+${integral} 积分`,
					state: '正常',
					is_delete: 0,
					time: time,
					create_time: nowdate,
					create_uid: uid,
					create_uname: 'job-day'
				});
				
				// 积分日志
				await dbtran.collection('wmzmall-integral-log').add({
					member_id: uid,
					member_uid: uid,
					integral: integral,
					ip: ip,
					type: '下单',
					content: `+${integral} 积分`,
					remark: `下单 +${integral} 积分`,
					state: '正常',
					is_delete: 0,
					time: time,
					create_time: nowdate,
					create_uid: uid,
					create_uname: 'job-day'
				});
			}
		}
	
		// 修改订单为已完成
		res.updateRes = await db.collection('wmzmall-order')
			.where({
				order_id: dbcmd.in(orderIds)
			})
			.update({
				state: '已完成',
				last_modify_time: nowdate,
				last_modify_uid: 'job-day'
			})
		
		res.addLogRes = await db.collection('wmzmall-order-log').add(orderLogs);
	}
	
	return res;
}

// 收货后 超过 15天，关闭售后入口
// overdue_day_close_aftersale
const doAfterSaleOrder = async (ip, orderParameter) => {
	const configTime = orderParameter.overdue_day_close_aftersale || 7;
	let count = 0;
	let res = {};
	do {
		// 订单关闭售后入口
		res = await afterSaleOrder(ip, configTime);
		count += res.count;
	} while (res.count >= 300)
	
	return count;
}
const afterSaleOrder = async (ip, configTime = 15) => {
	const nowdate = Date.now();
	const res = {
		count: 0
	};
	
	const orderRes = await db.collection('wmzmall-order')
		.where({
			// 0未售后 1售后中 2已售后 99禁止售后
			after_sale_state: 0,
			// 收货时间超过 15天
			received_time: dbcmd.lte(nowdate - configTime * 24 * 60 * 60 * 1000)
		})
		.field({
			state: true,
			order_id: true,
			create_uid: true
		})
		.limit(300)
		.get();
	
	if (orderRes.data && orderRes.data.length > 0) {
		res.count = orderRes.data.length;
	
		const orderIds = [];
		const orderLogs = [];
		
		for (let i = 0; i < orderRes.data.length; i++) {
			let order = orderRes.data[i];
			
			orderIds.push(order._id);
			orderLogs.push({
				order_id: order.order_id,
				log_type: '关闭售后',
				remark: `收货后超过 ${configTime} 天，关闭售后入口`,
				current_state: order.state,
				prev_state: order.state,
				ip: ip,
				is_delete: 0,
				create_uid: 'job-day',
				create_time: nowdate
			});
		}
	
		// 修改订单为已完成
		res.updateRes = await db.collection('wmzmall-order')
			.where({
				order_id: dbcmd.in(orderIds)
			})
			.update({
				after_sale_state: 99,
				last_modify_time: nowdate,
				last_modify_uid: 'job-day'
			})
		
		res.addLogRes = await db.collection('wmzmall-order-log').add(orderLogs);
	}
	
	return res;
}


// 处理已过期优惠券
const doExpireCoupon = async (ip) => {
	let count = 0;
	let res = {};
	do {
		// 已过期优惠券
		res = await expireCoupon(ip);
		count += res.count;
	} while (res.count >= 300)
	
	return count;
}
const expireCoupon = async (ip) => {
	const nowdate = Date.now();
	const res = {
		count: 0
	};
	
	const couponRes = await db.collection('wmzmall-marketing-coupon-rule')
		.where({
			is_delete: 0,
			// 状态 待激活|运营中|已过期
			state: '运营中',
			// 优惠券结束时间
			end_time: dbcmd.lte(nowdate)
		})
		.limit(300)
		.get();
	
	if (couponRes.data && couponRes.data.length > 0) {
		res.count = couponRes.data.length;
	
		const couponIds = couponRes.data.map(x => x._id);

		// 修改优惠券 rule 为已过期
		res.updateRes = await db.collection('wmzmall-marketing-coupon-rule')
			.where({
				_id: dbcmd.in(couponIds)
			})
			.update({
				state: '已过期',
				last_modify_time: nowdate,
				last_modify_uid: 'job-day'
			})
		
		// 批量修改优惠券为已过期
		res.updateRes = await db.collection('wmzmall-marketing-coupon')
			.where({
				coupon_id: dbcmd.in(couponIds),
				// 状态 待领取|已领取|已使用|已过期
				state: dbcmd.in(['待领取', '已领取'])
			})
			.update({
				state: '已过期',
				last_modify_time: nowdate,
				last_modify_uid: 'job-day'
			})
	}
	
	return res;
}


/**
 * 将 UTC+0 转换为 UTC+8
 */
function toDateUTC8(date) {
	// 小时 UTC+0 转换为 UTC+8
	date.setHours(date.getHours() + 8);
	return date;
}